<template>
  <div>
    <!-- 其他可能存在的组件或布局 -->
    <el-dialog v-model="registerDialogVisible" title="注册" width="500px">
      <el-form ref="registerForm" :model="user" :rules="rules" @submit.native.prevent="onSubmit">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="user.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="user.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="userID" label="用户ID">
          <el-input v-model="user.userID" placeholder="请输入用户ID"></el-input>
        </el-form-item>
        <el-form-item prop="userAddress" label="地址">
          <el-input v-model="user.userAddress" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item prop="phoneNumber" label="电话号码">
          <el-input v-model="user.phoneNumber" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="mb-4">
            <el-button type="primary" native-type="submit">注册</el-button>
          </div>
        </el-form-item>
      </el-form>
      <p v-if="message" :class="{'el-message': true, 'el-message--error': !success}">{{ message }}</p>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useStore } from 'vuex';

export default defineComponent({
  name: 'Register',

  setup() {
    const store = useStore();
    const user = ref({
      username: '',
      password: '',
      userID: '',
      userAddress: '',
      phoneNumber: '',
    });
    const message = ref('');
    const success = ref(false);
    const rules = {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      userID: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
    };

    // 使用Vuex管理dialogVisible状态
    const registerDialogVisible = computed({
      get: () => store.getters["auth/isRegisterDialogVisible"],
      set: value => store.commit('auth/TOGGLE_REGISTER_DIALOG', value),
    });

    const onSubmit = () => {
      registerForm.value.validate(valid => {
        if (valid) {
          user.value.registrationDate = new Date().toISOString().split('T')[0];
          axios.post('/register', user.value)
            .then(handleSuccess)
            .catch(handleError);
        } else {
          return false;
        }
      });
    };

    const handleSuccess = (response) => {
      if (response.status === 200) {
        message.value = '注册成功!';
        success.value = true;
        ElMessage({
          message: '注册成功，即将跳转至登录页面',
          type: 'success',
          duration: 1500,
          onClose: () => {
            registerDialogVisible.value = false;
            // 模拟跳转逻辑，实际应用中使用Vue Router
            // this.$router.push('/login');
          },
        });
      } else {
        handleError(response);
      }
    };

    const handleError = (error) => {
      let errMsg;
      if (error.response) {
        errMsg = error.response.data.message || '注册失败，请稍后再试';
      } else {
        errMsg = '网络请求失败，请检查网络连接';
      }
      message.value = errMsg;
      success.value = false;
      ElMessage({ message: errMsg, type: 'error' });
    };

    // 可能需要在组件挂载时初始化dialogVisible状态，根据具体需求调整


    return {
      user,
      message,
      success,
      rules,
      registerDialogVisible,
      onSubmit,
    };
  },
});

</script>

<style scoped>
.mb-4 {
  display: block;
  text-align: center;
  margin-bottom: 1rem;
}
</style>